const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);

/**
 * Git日志分析器 - 当GitLab API不可备用时使用本地git命令
 */
class GitAnalyzer {
  constructor() {
    this.repoPath = process.cwd(); // 默认使用当前目录
  }

  /**
   * 设置仓库路径
   */
  setRepoPath(path) {
    this.repoPath = path;
  }

  /**
   * 获取git提交日志
   * @param {string} since - 开始日期 (YYYY-MM-DD)
   * @param {string} until - 结束日期 (YYYY-MM-DD)
   * @returns {Array} 提交数据数组
   */
  async getCommits(since, until) {
    try {
      // 使用更安全的方式获取git日志，避免JSON解析问题
      const command = `git log --since="${since}" --until="${until}" --pretty=format:'START_COMMIT|%H|%h|%s|%an|%ae|%aI' --numstat`;
      
      console.log('执行git命令:', command);
      const { stdout, stderr } = await execAsync(command, { cwd: this.repoPath });
      
      if (stderr) {
        console.warn('Git命令警告:', stderr);
      }

      return this.parseGitLogSafe(stdout);
    } catch (error) {
      console.error('Git命令执行失败:', error);
      throw new Error(`无法获取git提交日志: ${error.message}`);
    }
  }

  /**
   * 解析git log输出（安全版本）
   */
  parseGitLogSafe(logOutput) {
    const commits = [];
    const lines = logOutput.trim().split('\n');
    
    let currentCommit = null;
    
    for (const line of lines) {
      if (line.startsWith('START_COMMIT')) {
        // 开始新的提交记录
        if (currentCommit) {
          commits.push(currentCommit);
        }
        
        // 解析提交信息
        const parts = line.split('|');
        if (parts.length >= 6) {
          currentCommit = {
            id: parts[1],
            short_id: parts[2],
            title: parts[3],
            message: parts[3], // 简化处理，使用标题作为消息
            author_name: parts[4],
            author_email: parts[5],
            created_at: parts[6],
            stats: {
              additions: 0,
              deletions: 0,
              total: 0
            }
          };
        }
      } else if (currentCommit && line.trim() && !line.startsWith('\t')) {
        // 解析文件统计信息 (格式: 添加行数\t删除行数\t文件名)
        const parts = line.split('\t');
        if (parts.length >= 2) {
          const additions = parseInt(parts[0]) || 0;
          const deletions = parseInt(parts[1]) || 0;
          currentCommit.stats.additions += additions;
          currentCommit.stats.deletions += deletions;
          currentCommit.stats.total += additions + deletions;
        }
      }
    }
    
    // 添加最后一个提交
    if (currentCommit) {
      commits.push(currentCommit);
    }
    
    console.log(`解析到 ${commits.length} 个git提交`);
    return commits;
  }

  /**
   * 获取当前仓库的远程URL
   */
  async getRemoteUrl() {
    try {
      const { stdout } = await execAsync('git config --get remote.origin.url', { cwd: this.repoPath });
      return stdout.trim();
    } catch (error) {
      console.warn('无法获取远程仓库URL:', error);
      return null;
    }
  }

  /**
   * 获取当前分支
   */
  async getCurrentBranch() {
    try {
      const { stdout } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: this.repoPath });
      return stdout.trim();
    } catch (error) {
      console.warn('无法获取当前分支:', error);
      return 'main';
    }
  }

  /**
   * 检查是否为git仓库
   */
  async isGitRepository() {
    try {
      await execAsync('git rev-parse --git-dir', { cwd: this.repoPath });
      return true;
    } catch (error) {
      return false;
    }
  }

  /**
   * 获取简化版的提交数据（兼容GitLab API格式）
   */
  async getCommitsCompatible(since, until) {
    const isGitRepo = await this.isGitRepository();
    if (!isGitRepo) {
      throw new Error('当前目录不是git仓库');
    }

    const commits = await this.getCommits(since, until);
    
    // 转换为兼容GitLab API的格式
    return commits.map(commit => ({
      id: commit.id,
      short_id: commit.short_id,
      title: commit.title,
      message: commit.message,
      author_name: commit.author_name,
      author_email: commit.author_email,
      created_at: commit.created_at,
      stats: commit.stats,
      // 添加一些兼容字段
      web_url: `#${commit.short_id}`,
      author_date: commit.created_at,
      committer_name: commit.author_name,
      committer_email: commit.author_email
    }));
  }
}

module.exports = GitAnalyzer;